﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Reflection;
using Deeper.Common;

namespace Deeper.DataAccess
{
	/// <summary>
	/// 关联
	/// </summary>
	public class Reference// : HColumnAttribute
	{
		/// <summary>
		/// 主表ID
		/// </summary>
		public string ParentCode { set; get; }
		/// <summary>
		/// 从表id
		/// </summary>
		public string ChildCode { set; get; }
		/// <summary>
		/// 父表
		/// </summary>
		public HTableAttribute ParentTable { set; get; }
		/// <summary>
		/// 子表
		/// </summary>
		public HTableAttribute ChildTable { set; get; }
		/// <summary>
		/// 系数
		/// </summary>
		public string Cardinality { set; get; }
		/// <summary>
		/// 父表关联键
		/// </summary>
		public HColumnAttribute ParentColumn { set; get; }
		/// <summary>
		/// 子表关联键
		/// </summary>
		public HColumnAttribute ChildColumn { set; get; }

		//public Reference(string Name)
		//{
		//    base.(Name);
		//}
	}


	public static class DatabaseScheme
	{
		/// <summary>
		/// 元数据集
		/// </summary>
		public static List<HTableAttribute> TableInfos = new List<HTableAttribute>();


		/// <summary>
		/// 获取实体类的表信息
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <returns></returns>
		public static HTableAttribute GetTableInfo(this Type type)
		{
			///如果缓存中有表信息，直接取出
			HTableAttribute currentTable = TableInfos.Find(s => s.EntityName.Equals(type.Name));
			if (currentTable != null) return currentTable;

			///获取实体属性
			var attribute = type.GetCustomAttributes(true).Where(attr => attr is HTableAttribute);
			///没有实体属性的就不是实体类
			if (attribute.ToList().Count == 0) throw new DeeperException(string.Format("类型【{0}】没有数据库映射信息，无法继续操作", type.ToString()));


			currentTable = (HTableAttribute)attribute.First();
			currentTable.EntityName = type.Name;
			///获取字段属性并赋值
			currentTable.Columns.AddRange(GetColumns(type));
			///添加到元数据集合
			TableInfos.Add(currentTable);

			return currentTable;
		}


		/// <summary>
		/// 获取全部字段列表信息
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <returns></returns>
		private static IList<HColumnAttribute> GetColumns(this Type type)
		{
			IList<HColumnAttribute> list = new List<HColumnAttribute>();
			(type.GetProperties()).ToList().ForEach(pi =>
			{
				HColumnAttribute ha;
				var attribute = pi.GetCustomAttributes(true).Where(attr => attr is HColumnAttribute);
				if (attribute.ToList().Count > 0)
				{
					ha = (HColumnAttribute)(attribute.First());
					ha.Field = pi;
					list.Add(ha);
				}
			});
			return list;
		}





	}
}
